const BASE_URL = 'http://localhost:3001';  // 修改为新的服务器地址

// 封装请求函数
const request = async (url, options = {}) => {
  // 获取用户信息
  const userInfo = wx.getStorageSync('userInfo');
  console.log('当前用户信息:', userInfo);

  // 构建请求数据
  let requestData = options.data || {};
  if (userInfo && userInfo.id) {
    requestData.user_id = parseInt(userInfo.id);
  }

  // 构建请求配置
  const requestOptions = {
    ...options,
    data: requestData
  };

  console.log('发起请求:', { url, options: requestOptions });
  console.log('=== 请求详情 ===');
  console.log('原始URL:', url);
  console.log('处理后的URL:', url);
  console.log('完整URL:', `${BASE_URL}${url}`);
  console.log('请求方法:', requestOptions.method || 'GET');
  console.log('请求数据:', requestData);
  console.log('请求头:', requestOptions.header);

  try {
    const response = await new Promise((resolve, reject) => {
      wx.request({
        url: `${BASE_URL}${url}`,
        ...requestOptions,
        success: (res) => {
          console.log('请求响应:', res);
          if (res.statusCode >= 200 && res.statusCode < 300) {
            resolve(res.data);
          } else {
            reject(res);
          }
        },
        fail: (error) => {
          console.error('请求失败:', error);
          reject(error);
        }
      });
    });

    console.log('请求成功:', response);
    return response;
  } catch (error) {
    console.error('请求失败:', error);
    throw error;
  }
};

// 旅行日记相关API
const diaryApi = {
  // 获取日记列表
  getDiaryList: async () => {
    try {
      const response = await request('/api/diaries', {
        method: 'GET'
      });
      console.log('获取日记列表响应:', response);
      return response;
    } catch (error) {
      console.error('获取日记列表失败:', error);
      throw error;
    }
  },

  // 获取日记详情
  getDiaryDetail: async (id) => {
    if (!id) {
      return Promise.reject(new Error('日记ID不能为空'));
    }
    try {
      const response = await request(`/api/diaries/${id}`, {
        method: 'GET'
      });
      console.log('获取日记详情响应:', response);
      return response;
    } catch (error) {
      console.error('获取日记详情失败:', error);
      throw error;
    }
  },

  // 创建日记
  createDiary: (data) => {
    return request('/api/diaries', {
      method: 'POST',
      data
    });
  },

  // 更新日记
  updateDiary: async (id, data) => {
    if (!id) {
      return Promise.reject(new Error('日记ID不能为空'));
    }
    try {
      const response = await request(`/api/diaries/${id}`, {
        method: 'PUT',
        data
      });
      console.log('更新日记响应:', response);
      return response;
    } catch (error) {
      console.error('更新日记失败:', error);
      throw error;
    }
  },

  // 删除日记
  deleteDiary: async (id) => {
    if (!id) {
      return Promise.reject(new Error('日记ID不能为空'));
    }
    try {
      const response = await request(`/api/diaries/${id}`, {
        method: 'DELETE'
      });
      console.log('删除日记响应:', response);
      return response;
    } catch (error) {
      console.error('删除日记失败:', error);
      throw error;
    }
  },

  // 上传图片
  uploadImage: (filePath) => {
    return new Promise((resolve, reject) => {
      console.log('=== 开始上传图片 ===');
      console.log('文件路径:', filePath);
      
      wx.uploadFile({
        url: `${BASE_URL}/api/upload`,
        filePath: filePath,
        name: 'file',
        header: {
          Authorization: `Bearer ${wx.getStorageSync('token')}`
        },
        success: (res) => {
          console.log('=== 上传响应 ===');
          console.log('状态码:', res.statusCode);
          console.log('响应数据:', res.data);
          
          if (res.statusCode === 200) {
            try {
              const data = JSON.parse(res.data);
              console.log('解析后的响应数据:', data);
              
              if (data && data.url) {
                // 确保URL是完整的
                let imageUrl = data.url;
                
                // 如果URL不是以http开头，添加BASE_URL
                if (!imageUrl.startsWith('http')) {
                  imageUrl = `${BASE_URL}${imageUrl}`;
                }
                
                console.log('最终图片URL:', imageUrl);
                resolve(imageUrl);
              } else {
                console.error('响应数据格式错误:', data);
                reject(new Error('上传失败：服务器返回数据格式错误'));
              }
            } catch (error) {
              console.error('解析响应数据失败:', error);
              reject(new Error('上传失败：解析响应数据失败'));
            }
          } else {
            console.error('上传失败，状态码:', res.statusCode);
            reject(new Error(`上传失败：服务器返回状态码 ${res.statusCode}`));
          }
        },
        fail: (err) => {
          console.error('上传请求失败:', err);
          reject(new Error(`上传失败：${err.errMsg || '网络请求失败'}`));
        }
      });
    });
  }
};

module.exports = {
  request,
  diaryApi,
  BASE_URL
}; 